package com.uiotsoft.small.app.entity;

import com.uiotsoft.small.mqtt.MqttClientOld;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;

@Slf4j
public class AppClient extends BaseAppClient{
    public AppClient(String env, String mobile, String si, String sn) {
        super(env, mobile, si, sn);
    }

    /**
     * mqtt连接
     */
    public boolean connect() throws MqttException {
        myMqttClient = new MqttClientOld(mqttUrl, clientId);
        myMqttClient.setAppKey(appKey);
        myMqttClient.setAppSecret(appSecret);
        log.debug("\n******初始化成功……\n******APP客户端是：{}",super.toString());
        myMqttClient.setMqttClient(options(), null);
        myMqttClient.subscribe(subTopic);
        log.debug("\n******连接成功，订阅成功……\n******APP的mqttClient是：{}", myMqttClient.toString());
        return myMqttClient.getMqttClient().isConnected();
    }

    /**
     * 设置连接属性
     * @return
     */
    public MqttConnectOptions options() {
        MqttConnectOptions options = new MqttConnectOptions();
        options.setMqttVersion(3);
        options.setUserName(username);
        options.setPassword(password.toCharArray());
        options.setConnectionTimeout(10);
        options.setKeepAliveInterval(30);
        //options.setMaxReconnectDelay(5);
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        //设置遗嘱
        String willTopic;
        if (env.toLowerCase().endsWith("local")) {
            willTopic = getATHTopic("mqttConnect", "lanAppOffLine");
        } else {
            willTopic = getATHTopic("mqttConnect", "appOffLine");
        }
        options.setWill(willTopic, getWillData(), 1, true);
        log.debug("\n******设置遗嘱成功……{}", willTopic);
        return options;
    }

}
